<template>
  <div>
    <el-dialog
      title="用户注册"
      :visible.sync="dialogVisible"
      width="600px"
      style="text-align:center; "
      @close="handleClose"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="头像 " prop="avatar">
          <!-- action  上传的地址 -->
          <!-- show-file-list 是否显示列表 -->
          <!-- before-upload 上传之前(用来限定上传图片的格式大小) -->
          <!-- on-success 上传之后的(预览和给ruleForm.imageUrl赋值) -->
          <el-upload
            class="avatar-uploader"
            :action="imgUrl"
            :data="uploadObj"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称 " prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱 " prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机 " prop="phone">
          <el-input v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码 " prop="password">
          <el-input v-model="ruleForm.password" show-password></el-input>
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="16"
            ><div class="grid-content bg-purple">
              <el-form-item label="图形码" prop="code">
                <el-input v-model="ruleForm.code"></el-input>
              </el-form-item></div
          ></el-col>
          <el-col :span="7"
            ><div class="grid-content bg-purple">
              <img :src="picUrl" alt="" @click="getPicUrl" /></div
          ></el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="16"
            ><div class="grid-content bg-purple">
              <el-form-item label="验证码" prop="rcode">
                <el-input v-model="ruleForm.rcode"></el-input>
              </el-form-item></div
          ></el-col>
          <el-col :span="8"
            ><div class="grid-content bg-purple">
              <el-button style="width:100%" @click="getPhoneCode"
                >获取用户验证码</el-button
              >
            </div></el-col
          >
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      uploadObj: {},
      imgUrl: process.env.VUE_APP_BASEURL + '/uploads', // 上传头像的地址
      imageUrl: '',
      picUrl: process.env.VUE_APP_BASEURL + '/captcha?type=login',
      dialogVisible: false,
      ruleForm: {
        avatar: '',
        username: '',
        email: '',
        phone: '',
        password: '',
        code: '',
        rcode: ''
      },
      rules: {
        avator: [
          { required: true, message: '头像不能为空', trigger: 'change' }
        ],
        username: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 4, max: 6, message: '长度在 4 到 6 个字符', trigger: 'blur' }
        ],
        email: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('邮箱不能为空'))
                return
              }
              const getEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
              if (!getEmail.test(value)) {
                callback(new Error('邮箱格式不正确'))
                return
              }
              callback()
            },
            trigger: 'blur',
            required: true
          }
        ],
        phone: [
          {
            validator: (rules, value, callback) => {
              if (!value) {
                callback(new Error('手机号不能为空'))
                return
              }
              const reg = /^1[3-9][0-9]{9}$/
              if (!reg.test(value)) {
                callback(new Error('手机号不合法'))
                return
              }
              callback()
            },
            trigger: 'blur',
            required: true
          }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        code: [
          { required: true, message: '请输入图形码', trigger: 'blur' },
          { min: 4, max: 4, message: '长度为 4 个字符', trigger: 'blur' }
        ],
        rcode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
          //   { min: 4, max: 4, message: '长度为 4 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    //   图形码点击刷新
    getPicUrl () {
      this.picUrl =
        process.env.VUE_APP_BASEURL + '/captcha?type=sendsms&t=' + Date.now()
    },
    //   头像上传后获得响应返回的结果,将结果赋值到avatar中,表单提交时上传
    handleAvatarSuccess (res, file) {
      if (res.code === 200) {
        this.imageUrl = URL.createObjectURL(file.raw)
        this.ruleForm.avatar = res.data.file_path
        // console.log(this.ruleForm.avatar)
      } else {
        this.$message({
          message: res.data.message,
          type: 'error',
          duration: 1000
        })
      }
    },
    // 头像上传之前的格式大小限定
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/png/gif 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      // 给上传头型添加额外参数（这个是后台要求的）, image 属性是接口中规定的
      this.uploadObj.image = file
      return isJPG && isLt2M
    },
    //   校验手机号码和图形码获得验证码
    async getPhoneCode () {
      let num = 0
      this.$refs.ruleForm.validateField(['phone', 'code'], errorMessage => {
        if (!errorMessage) {
          num++
        }
      })
      if (num === 2) {
        //   await命令后面是一个Promise对象,返回该对象的结果.可以省略写.then获得结果,方便快捷,被称为语法糖,
        //   必须与async搭配使用 , 是一个键值对
        const res = await this.$axios.post('/sendsms', {
          phone: this.ruleForm.phone,
          code: this.ruleForm.code
        })
        // console.log(res)
        if (res.data.code === 200) {
          this.ruleForm.rcode = res.data.data.captcha
        } else {
          this.$message({
            message: res.data.message,
            type: 'erroe',
            duration: 500 // duration弹框出现显示的时间
          }) // this.$message 方法是element-ui里面方便简洁的弹框提示,与alert作用相同

          //           this.$message({
          // message:“这是弹框消息”,
          // type:‘success’
          // })
          // type 取值 ‘success’(成功) /warning(警告)/info(消息)/error(错误)/;
          this.getPicUrl()
        }
      }
    },
    // 完成表单校验并提交
    submit () {
      this.$refs.ruleForm.validate(async valid => {
        // console.log(valid)
        if (!valid) return // 判断表单校验是否通过,验证所有输入是否完成,通过则返回turn

        const res = await this.$axios.post('/register', this.ruleForm)
        // console.log(res)
        if (res.data.code === 200) {
          this.$message({
            message: '注册成功',
            type: 'success',
            duration: 1000
          })
          this.dialogVisible = false
        } else {
          this.$message({
            message: res.data.message,
            type: 'error',
            duration: 1000
          })
          this.getPicUrl()
        }
      })
    },
    handleClose () {
      this.$refs.ruleForm.resetFields()

      // 别忘记清空图片
      this.imageUrl = ''
    }
  }
}
</script>
<style>
.el-dialog__header {
  background: linear-gradient(270deg, #01c6fa, #1493fa);
}
.dialog-footer {
  text-align: center;
}

/* 头像上传 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
